package gagnatech.controller;



import gagnatech.service.ServiceCategory;
import gagnatech.service.ServiceMedia;
import java.util.ArrayList;
import java.util.List;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

import gagnatech.entity.Category;
import gagnatech.entity.Media;
import gagnatech.service.ServiceCategory;
import gagnatech.service.ServiceMedia;

public class ControlerCategory {

	private ServiceCategory serviceCategory;
	private ServiceMedia serviceMedia;

	private List<SelectItem> listCategory;
	private String category;
	private Media media;
	
	private DataModel listMedia;

	public ControlerCategory() {
		serviceCategory = new ServiceCategory();
		serviceMedia = new ServiceMedia();
		listMedia = new ListDataModel();
		media = new Media();
	}

	public DataModel getListMedia() {
		int index = getIndex(category, listCategory);
		if(index!=-1) {
			index = index + 1;
			listMedia.setWrappedData(serviceMedia.getManagerMedia().getMediaByIdCategory(index));
		}
		return listMedia;	
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public List<SelectItem> getListCategory() {

		if (listCategory == null) {
			listCategory = new ArrayList<SelectItem>();
			for (String val : addItem()) {
				listCategory.add(new SelectItem(val));
			}
		}
		return listCategory;
	}

	public String detailMedia() {
		media = (Media) listMedia.getRowData();
		return "detailMedia";
	}

	public Media getMedia() {
		return media;
	}

	public void setMedia(Media media) {
		this.media = media;
	}

	public void setListCategory(List<SelectItem> listCategory) {
		this.listCategory = listCategory;
	}

	public Iterable<String> addItem() {
		
		ArrayList<String> list = new ArrayList<String>();
		
		List<Category> listCategory = serviceCategory.getManagerCategory().getAllCategory();
		for (Category category : listCategory) {
			list.add(category.getName());	
		}

		return list;
	}

	private int getIndex(String label, List<SelectItem> list) {
	    if ((list == null) || list.isEmpty()) return -1;
	    int i;
	    for(i=0; i < list.size(); i++)
	        if (list.get(i).getLabel().equals(label)) return i;

	    return -1;
	}

	public String find() {
		return null;
	}
}

